//
//  SEWebViewController.swift
//  SmartEyeForDoctor
//
//  Created by QDSG on 2021/6/10.
//

import UIKit
import WebKit

private let kEstimatedProgress = "estimatedProgress"

class SEWebViewController: SEBaseViewController {
    
    deinit {
        webView.removeObserver(self, forKeyPath: kEstimatedProgress)
    }
    
    private var url: URL?
    
    convenience init(url: URL?, title: String? = nil) {
        self.init()
        self.url = url
        self.title = title
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        webView.addObserver(self, forKeyPath: kEstimatedProgress, options: .new, context: nil)
        
        if let url = url {
            webView.load(URLRequest(url: url))
        }
    }

    override func setupUI() {
        view.addSubview(webView)
        webView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().priority(.low)
            make.top.equalToSuperview().offset(UIScreen.navigationBarMaxY)
        }
        
        view.addSubview(progressView)
        progressView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(2)
            make.top.equalToSuperview().offset(UIScreen.navigationBarMaxY)
        }
    }
    
    override func setupNavBar() {
        super.setupNavBar()
        
    }
    
    override func popBack() {
        if webView.canGoBack {
            webView.goBack()
        } else {
            navigationController?.popViewController(animated: true)
        }
    }

    private lazy var webView: WKWebView = {
        let webView = WKWebView()
        webView.allowsBackForwardNavigationGestures = true
        webView.navigationDelegate = self
        return webView
    }()
    
    private lazy var progressView: UIProgressView = {
        let progress = UIProgressView()
        progress.progressTintColor = Asset.main.color
        progress.trackTintColor = .clear
        return progress
    }()

}

// MARK: - WKNavigationDelegate

extension SEWebViewController: WKNavigationDelegate {
    /// 页面加载完成之后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        progressView.setProgress(0.0, animated: false)
        navigationItem.title = title ?? (webView.title ?? webView.url?.host)
    }
    
    /// KVO 监听进度 必须实现此方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if let obj = object as? WKWebView, obj == webView {
            if keyPath == kEstimatedProgress {
                progressView.isHidden = webView.estimatedProgress >= 1.0
                progressView.setProgress(Float(webView.estimatedProgress), animated: true)
            }
        } else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }
}
